package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.util.StringUtil;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.fn.server.productRequire.ProductRequireItemRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("requireAutoGeneratorOrderService")
public class RequireAutoGeneratorOrderService {
    @Autowired
    private BusinessParamRepository businessParamRepository;
    @Autowired
    private ProductRequireItemRepository productRequireItemRepository;
    @Autowired
    private ReplenishmentManagementNewService replenishmentManagementNewService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    // 定时任务要货自动转储
    public void time() {
        this.timeInner(null);
    }
    public void timeInner(SimpleRequest param) {
        JSONObject getJO = param == null?null:param.getJO();
        String id = getJO == null?"":getJO.getString("requireId");
        List<BusinessParam> businessParams = businessParamRepository.findAllByQueryKey("offlineRequireWeight");
        List<String> bpValues = businessParams.stream().map(businessParam -> businessParam.getValue().split(",")).flatMap(Arrays::stream).collect(Collectors.toList());

        List<Map> requireLocationInfo = productRequireItemRepository.offlineProductRequireLocation(bpValues);

        requireLocationInfo.forEach(locationItem -> {
            execute(() -> {
                SimpleRequest request = new SimpleRequest();
                String requireId = locationItem.get("ID").toString();
                if (!StringUtils.isEmpty(id) && !id.equals(requireId)) return;

                // 查询能够转储的数据
                request.setData(MapUtil.mapper("requireId", requireId, "commodityInquiryOrderId", true, "autoDumpChanelIds", bpValues, "dumpChannelType", Arrays.asList(1, 4)));
                List<Map> condiMetRequireData;
                try {
                    condiMetRequireData = replenishmentManagementNewService.queryRequireItem(request);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    return;
                }
                condiMetRequireData.forEach(requireData -> {
                    requireData.put("selectFlag", true);
                });

                // 组装转储信息
                request = new SimpleRequest();
                request.setData(MapUtil.mapper("productRequireItems", condiMetRequireData));
                JSONObject sumRequireData;
                try {
                    sumRequireData = replenishmentManagementNewService.dumpSum(request);
                    sumRequireData.getJSONArray("sumProductRequireItems").forEach(requireData -> {
                        ((JSONObject) requireData).put("checkData", true);
                    });
                    Location location = SpringManager.getBean(LocationRepository.class).findOne(locationItem.get("F_LOCATION_ID").toString());
                    sumRequireData.put("location", new JSONObject(MapUtil.mapper("id", location.getId(), "company", new JSONObject(MapUtil.mapper("id", location.getCompany().getId())))));
                    sumRequireData = SpringManager.getBean(RepleDumpSumItemService.class).obtainStock(sumRequireData);
                } catch (Exception e) {
                    return; // 想阻止我继续下一条？没门，继续 go
                }

                // 生成转储订单
                SimpleRequest request3 = new SimpleRequest();
                sumRequireData.put("queryCondiAndItem", new JSONObject());
                request3.setData(sumRequireData);
                try {
                    replenishmentManagementNewService.generatorDumpOrder(request3);
                } catch (Exception e) {
                    if (e.getMessage().indexOf("未获取到有效数据！请检查是否填写转储数量") != -1) return; // 嗯, 正常的, 继续 go
                    throw new RuntimeException(e.getMessage());
                }
            });
        });

    }


    @Listener(topic = "event:requireAutoGeneratorOrderService.autoPurOrder")
    public void autoPurOrder(SimpleRequest params) {
        JSONObject param = params.getJO();

        // 外采直接采购返回
        Map isWCFlag = SpringManager.getBean(ExternalInquiryRequirePurOrderService.class).sendOrder(param);
        if (Boolean.valueOf(isWCFlag.get("isWC").toString())) return;


        // 非外采生成采购订单
        SimpleRequest request = new SimpleRequest();
        request.setData(MapUtil.mapper("requireId", param.get("id"), "commodityInquiryOrderIdPurchase", true, "purchaseGroupIdIsNotNull", true, "mainChanelType", "80"));
        List<Map> condiMetRequireData;
        try {
            condiMetRequireData = replenishmentManagementNewService.queryRequireItem(request);
        } catch (Exception e) {
            return;
        }
        condiMetRequireData.forEach(requireData -> {requireData.put("selectFlag", true);});

        // 获取价格、合同信息
        request = new SimpleRequest();
        request.setData(MapUtil.mapper("productRequireItems", condiMetRequireData));
        JSONObject purchaseRequireInfoExpand;
        try {
            purchaseRequireInfoExpand = replenishmentManagementNewService.purchaseSum(request);
            JSONArray purchaseRequireItems = purchaseRequireInfoExpand.getJSONArray("purchaseRequireItems");
            JSONArray checkRequireItems = purchaseRequireItems.stream().filter(item -> ((JSONObject) item).getDoubleValue("P001") != 0).collect(Collectors.toCollection(JSONArray::new));
            if (checkRequireItems.isEmpty()) return; // 没有匹配到合适的合同等数据
        } catch (Exception e) {
            return;
        }

        // 生成采购
        purchaseRequireInfoExpand.getJSONArray("purchaseRequireItems").forEach(requireData -> {((JSONObject) requireData).put("checkData", true);});
        request = new SimpleRequest();
        request.setData(purchaseRequireInfoExpand);
        replenishmentManagementNewService.generatorPurOrder(request);
    }

    @FunctionalInterface
    public interface Callback {
        @Nullable
        void execute();
    }


    public void execute(Callback callback) {
        transactionTemplate.execute(status -> {
            try {
                callback.execute();
                return null;
            } catch (Exception e) {
                status.isRollbackOnly();
                throw e;
            }
        });
    }
}
